#!/usr/bin/env python
# -*- encoding:utf8 -*-

import os
import re
import sys

curdir = os.path.dirname(os.path.abspath(__file__))
rootdir = os.path.dirname(curdir)
project = os.path.basename(curdir)
modules = (s for s in os.listdir(rootdir) if s.startswith(project) and os.path.isdir(os.path.join(rootdir, s)))

def prompt():
  print('''\
    1. python manager.py
    2. python manager.py list
    3. python manager.py git [args]
  ''')

if __name__ == '__main__':
  if len(sys.argv) == 1:
    prompt()
    sys.exit()

  if sys.argv[1] == 'list':
    for module in modules:
      print(os.path.join(rootdir, module))
  elif sys.argv[1] == 'git':
    for module in modules:
      print('-' * 30, module , '-' * 30)
      os.chdir(os.path.join(rootdir, module))
      args = sys.argv[2:]
      args.insert(0, 'git')
      args = list(map(lambda arg:'"{}"'.format(arg) if re.search(r'\s+', arg) else arg, args))
      retval = os.popen(' '.join(args)).read()
      print(retval)
    else:
      os.chdir(curdir)
  else:
    print('error: "{}" command does not exists!'.format(sys.argv[1]))
    prompt()
